<?php

namespace App\Models;

//use Encore\Admin\Traits\DefaultDatetimeFormat;
use App\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\DB;

/**
 * Class Menu.
 *
 * @property int $id
 *
 * @method where($parent_id, $id)
 */
class NewMenu extends Model
{

   /* use DefaultDatetimeFormat;
    use ModelTree {
        ModelTree::boot as treeBoot;
    }*/

    use ModelTree;

    protected $table = 'yt_new_menu';
//    protected $table = 'admin_menu';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['parent_id', 'order', 'title', 'uri', 'permission', 'active'];

    /**
     * Create a new Eloquent model instance.
     *
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        $connection = config('admin.database.connection') ?: config('database.default');

        $this->setConnection($connection);

        $this->setTable($this->table);

        parent::__construct($attributes);
    }


  /*  protected static function boot()
    {
        static::treeBoot();

        static::deleting(function ($model) {
            $model->roles()->detach();
        });
    }*/


    // 获取顶级模块名称
    static function topParentName($id)
    {
        do {
            $parent = self::find($id);
            $id = $parent->parent_id;

        } while ($id > 0);

//        return $parent->title;
        return $parent;
    }

    // 获取该页面对应菜单名称& 顶级模块名称
    static function getPageName($path)
    {
        $path = str_replace('admin', '',$path);
        $path = preg_replace('/(\/[\d]+)[\/a-zA-Z0-9]*/', '',$path);
//        \Log::info($path);
        $path = str_replace('/save','', $path);
        $menu = self::where('uri', $path)
            ->orWhere('uri',ltrim($path,'/'))// 去掉左斜杠
            ->first();
        if (!$menu) {
            return   [
                'page'=> $path,
                'module'=> 'Undefined',
            ];
        }
        return  [
            'page'=> $menu['title'],
            'module'=> self::topParentName($menu->id)->title,
            'page_id'=> $menu['id'],
            'module_id'=> self::topParentName($menu->id)->id,
        ];

    }


    public function scopeIsActive($qry)
    {
        return $qry->where('active',1);
    }



    public function roles(): BelongsToMany
    {
        $pivotTable = config('admin.database.role_menu_table');
//        $pivotTable = 'yt_new_role_menu';
//        $relatedModel = config('admin.database.roles_model');

        return $this->belongsToMany(NewRole::class, $pivotTable, 'menu_id', 'role_id');
    }







    // 登入用户拥有的菜单权限
    /*public function myNodes()
    {
        $orderColumn = DB::getQueryGrammar()->wrap($this->orderColumn);
        $byOrder = $orderColumn.' = 0,'.$orderColumn;

        $self = new static();

        if ($this->queryCallback instanceof \Closure) {
            $self = call_user_func($this->queryCallback, $self);
        }

        return $self->whereIn('id', [10,11,0,8,1])->orderByRaw($byOrder)->get()->toArray();
    }*/




    public function parent()
    {
        return $this->belongsTo(static::class, 'parent_id');
    }

}
